package com.xuecheng.media.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xuecheng.media.model.po.MediaProcess;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author itcast
 */
public interface MediaProcessMapper extends BaseMapper<MediaProcess> {
    /**
     * 查询待处理任务
     *
     * @param shardIndex 任务分片索引
     * @param shardTotal 总分片数
     * @param count      任务数
     * @return
     */
//    @Select("select * from media_process where (status = '1' or status = '3') and id % #{shardToal} = #{shardIndex} and fail_count <3  limit #{count}")
    @Select("select * from media_process t where t.id % #{shardTotal} = #{shardIndex} and (t.status = '1' or t.status = '3') and t.fail_count < 3 limit #{count}")
    List<MediaProcess> selectListByShardIndex(@Param("shardIndex") int shardIndex,
                                              @Param("shardTotal") int shardTotal,
                                              @Param("count") int count);

    /**
     * 开启任务，修改任务状态，这里使用数据库级别的乐观锁，控制任务别重复查询到，导致任务重复执行
     *
     * @param id
     * @return
     */
    @Update("update media_process m set m.status = '4' where (m.status = '1' or m.status = '3') and m.id = #{id} and m.fail_count <3")
    int startTask(@Param("id") Long id);

}
